<!--数据查询  -->
<template>
  <div class="dataQuery" :style="styleObj">
    <el-card class="head">
      <el-form ref="FtuForm" :model="formData" label-width="10px" size="mini">
        <el-row>
          <el-col :span="3">
            <el-form-item prop="gw_sn">
              <el-select
                style="width: 100%"
                v-model="formData.gw_sn"
                placeholder="请选择方阵"
                clearable
                @change="GWselectChange"
              >
                <el-option
                  v-for="(item, index) in GwList"
                  :label="item.name"
                  :value="item.id"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item prop="term_key">
              <el-select
                style="width: 100%"
                v-model="formData.term_key"
                placeholder="请选择单机"
                clearable
                @change="ZDselectChange"
              >
                <el-option
                  v-for="(item, index) in ZdList"
                  :label="item.name"
                  :value="item.id"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item prop="from">
              <el-select
                style="width: 100%"
                v-model="formData.from"
                placeholder="请选择数据类型"
                @change="selectChange"
                clearable
              >
                <el-option label="遥信" value="data-yx"></el-option>
                <el-option label="遥测" value="data-yc"></el-option>
                <el-option label="遥脉" value="data-ym"></el-option>
                <el-option label="定时任务" value="data-task"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item prop="id">
              <el-select
                ref="optionRef"
                style="width: 100%"
                v-model="formData.id"
                placeholder="请选择查询的数据"
                clearable
              >
                <el-option
                  v-for="(item, index) in dataIdList"
                  :label="item.name"
                  :value="item.id"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="开始时间" prop="beginTime" label-width="70px">
              <el-date-picker
                style="width: 100%"
                v-model="formData.beginTime"
                type="datetime"
                range-separator=":"
                placeholder="选择开始日期时间"
                value-format="yyyy-MM-dd HH:mm:ss"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="结束时间" prop="endTime" label-width="70px">
              <el-date-picker
                style="width: 100%"
                v-model="formData.endTime"
                type="datetime"
                range-separator=":"
                placeholder="选择结束日期时间"
                value-format="yyyy-MM-dd HH:mm:ss"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <!-- <div style="margin-left: 30px"> -->
            <el-button size="mini" type="primary" @click="query"
              >查询</el-button
            >
            <el-button size="mini" type="danger" @click="resset"
              >重置</el-button
            >
            <el-button type="success" size="mini" @click="exportButton"
              >导出</el-button
            >
            <!-- </div> -->
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-tabs
      class="query-tab"
      stretch
      @tab-click="handleClick"
      style="height: auto"
    >
      <el-tab-pane label="图形展示">
        <div v-if="myChartShow">
          <div
            id="line"
            :style="{ height: styleObj.tableHeight, width: '100%' }"
            ref="myChart"
          ></div>
        </div>
        <div v-else>
          <div slot="empty" style="color: black">
            <el-empty description="哎呀,你是不是忘记查询啦!"></el-empty>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="报表展示">
        <ux-grid
          id="myTable"
          class="tableListValue"
          :key="random"
          :data="TableList"
          ref="plxTable"
          :max-height="styleObj.tableHeightCopy"
          stripe
          :border="false"
          size="mini"
          :header-cell-style="{ 'text-align': 'center' }"
          style="width: 100%; font-size: 12px"
          v-loading="Tableloading"
          element-loading-text="拼命加载中"
          element-loading-spinner="el-icon-loading"
          :highlight-current-row="true"
          show-overflow
        >
          <ux-table-column
            v-for="(item, index) in columns"
            :key="index"
            :title="item.label"
            :field="item.prop"
            :align="item.align"
            :width="item.width"
            resizeable
          >
          </ux-table-column>
          <div slot="empty" style="color: black">
            <el-empty description="哎呀,你是不是忘记查询啦!"></el-empty>
          </div>
        </ux-grid>
        <div v-show="TableList.length > 0">
          <b>共 {{ TableList.length }} 条</b>
        </div>
      </el-tab-pane>
    </el-tabs>
    <!-- </div> -->
  </div>
</template>

<script>
import { myStorage } from "@/utils/localStorage";
import YgTable from "@/components/Table/YgTable.vue";
import { exportDataToExcel } from "@/utils/exportExcelBlob/index";
import {
  setMessageCallback,
  publishMsg,
  removeMessageCallback,
  checkSpecialId,
} from "@/mqtt";
export default {
  //import引入的组件需要注入到对象中才能使用
  name: "widgetDataQuery",
  components: {
    YgTable,
  },
  props: {
    value: Object,
    ispreview: Boolean,
  },
  data() {
    //这里存放数据
    return {
      columns: [
        {
          prop: "datetime",
          label: "更新时间",
        },
        {
          prop: "value",
          label: "值/(单位)",
        },
      ],
      TableList: [],
      formData: {
        gw_sn: "",
        term_key: "",
        from: "",
        id: "",
        beginTime: "",
        endTime: "",
      },
      myChart: null,
      myChartX: [],
      myChartY: [],
      title: "",
      myChartName: "",
      myChartShow: false,
      dataIdList: [],
      yxList: [],
      ycList: [],
      ymList: [],
      taskList: [],
      Tableloading: false,
      options: {},
      random: 1,
      GwList: [],
      ZdList: [],
    };
  },
  computed: {
    transStyle() {
      return this.objToOne(this.options);
    },
    styleObj() {
      return {
        position: this.ispreview ? "absolute" : "static",
        width: this.transStyle.width + "px",
        height: this.transStyle.height + "px",
        tableHeight: this.transStyle.height - 74 + "px",
        tableHeightCopy: this.transStyle.height - 74,
        left: this.transStyle.left + "px",
        top: this.transStyle.top + "px",
        background: this.transStyle.background,
        opacity: this.transStyle.transparency / 100,
      };
    },
  },
  //监控data中的数据变化
  watch: {
    value: {
      handler(val) {
        this.options = val;
        this.refresh();
      },
      deep: true,
    },
    TableList: {
      deep: true,
      handler: function (val, oldval) {
        if (val.length > 0) {
          this.$nextTick(() => {
            this.renderMychart();
          });
        }
      },
    },
  },
  //方法集合
  methods: {
    //刷新组件
    refresh() {
      this.random = new Date().getTime() * 1000 + (this.random++ % 1000);
    },
    query() {
      this.TableList = [];
      // this.dataIdList = []
      this.myChartX = [];
      this.myChartY = [];
      let newMsg = {
        webMsgType: 1020,
        funCode: 0,
      };
      let objParam = {
        from: this.formData.from,
        id: this.formData.id,
        beginTime: this.formData.beginTime,
        endTime: this.formData.endTime,
      };
      newMsg.data = objParam;
      publishMsg(newMsg);
      this.Tableloading = true;
    },
    resset() {
      this.$refs.FtuForm.resetFields();
    },
    exportButton() {
      if (this.TableList.length <= 0) {
        this.$message.warning("请查询数据后再导出！");
      } else {
        let datas = [];
        this.TableList.forEach((el) => {
          datas.push({
            更新时间: el.datetime,
            值: el.value,
          });
        });
        let fileName = this.$refs.optionRef.selected.label;
        exportDataToExcel(datas, fileName + ".xlsx");
      }
    },
    timerChart() {
      setTimeout(() => {
        this.renderMychart();
      }, 100);
    },
    handleClick(tab) {
      if (tab.index === "0") {
        this.myChartShow = true;
        this.timerChart();
      }
      if (tab.index === "1") {
        this.myChartShow = false;
        this.refresh();
      }
    },
    selectChange(val) {
      this.dataIdList.splice(0, this.dataIdList.length);
      switch (val) {
        case "data-yx":
          let newMsgyx = {
            webMsgType: 1009,
            funCode: 0,
          };
          newMsgyx.data = {
            gw_sn: this.formData.gw_sn,
            term_key: this.formData.term_key,
          };
          publishMsg(newMsgyx);
          this.formData.id = "";
          this.dataIdList = this.yxList;
          break;
        case "data-yc":
          let newMsgyc = {
            webMsgType: 1010,
            funCode: 0,
          };
          newMsgyc.data = {
            gw_sn: this.formData.gw_sn,
            term_key: this.formData.term_key,
          };
          publishMsg(newMsgyc);
          this.formData.id = "";
          this.dataIdList = this.ycList;
          break;
        case "data-ym":
          let newMsgym = {
            webMsgType: 1011,
            funCode: 0,
          };
          newMsgym.data = {
            gw_sn: this.formData.gw_sn,
            term_key: this.formData.term_key,
          };
          publishMsg(newMsgym);
          this.formData.id = "";
          this.dataIdList = this.ymList;
          break;
        case "data-task":
          let newMsgtask = {
            webMsgType: 1015,
            funCode: 0,
          };
          newMsgtask.data = {
            gw_sn: this.formData.gw_sn,
            term_key: this.formData.term_key,
          };
          publishMsg(newMsgtask);
          this.formData.id = "";
          this.dataIdList = this.taskList;
          break;
        default:
          break;
      }
    },
    GWselectChange(val) {
      this.formData.term_key = "";
      this.formData.id = "";
      this.formData.from = "";
      this.dataIdList.splice(0, this.dataIdList.length);
      publishMsg({
        webMsgType: 1008, //发送请求终端消息
        funCode: 0,
        data: { gw_sn: val },
      });
    },
    ZDselectChange(val) {
      this.dataIdList.splice(0, this.dataIdList.length);
      this.formData.from = "";
      this.formData.id = "";
    },
    renderMychart() {
      if (
        this.myChart != null &&
        this.myChart != "" &&
        this.myChart != undefined
      ) {
        this.myChart.dispose(); //销毁
      }
      this.myChart = this.$echarts.init(this.$refs.myChart);
      var options = {
        tooltip: {
          trigger: "axis",
          backgroundColor: "rgb(18,255,254,0.4)",
          barderColor: "#12fffe",
        },
        title: {
          text: `${this.myChartName}曲线图`,
          left: "center",
          textStyle: {
            fontSize: 18,
            fontWeight: "normal",
            color: "#fff",
          },
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data: this.myChartX,
          axisLabel: {
            textStyle: {
              color: "rgb(0,253,255,0.8)",
            },
          },
          axisLine: {
            show: true, //隐藏X轴轴线
            lineStyle: {
              color: "#12fffe",
            },
          },
          splitLine: {
            show: false,
          },
        },
        yAxis: {
          type: "value",
          name: this.title,
          nameTextStyle: {
            color: "#ffffff",
          },
          axisLabel: {
            margin: 10,
            textStyle: {
              color: "rgb(0,253,255,0.8)",
            },
          },
          axisLine: {
            show: true, //隐藏Y轴轴线
            lineStyle: {
              color: "#12fffe",
            },
          },
          splitLine: {
            show: false,
          },
        },
        series: [
          {
            name: this.title,
            data: this.myChartY,
            type: "line",
            lineStyle: {
              normal: {
                color: "#12fffe", // 线条颜色
              },
              borderColor: "#f0f",
            },
          },
        ],
      };
      this.myChart.setOption(options, true);
      window.addEventListener("resize", () => {
        this.myChart.resize();
      });
    },
    onMessage(topic, msg) {
      // console.log("正在监听--终端页面数据", topic, msg);
      switch (msg.webMsgType) {
        case 1020:
          if (checkSpecialId(msg)) {
            switch (msg.funCode) {
              case 0:
                if (msg.retCode != 0 || !msg.data) {
                  return this.$message.error(msg.retMsg);
                }
                this.title = msg.data.unit;
                this.myChartName = msg.data.name;
                if (msg.data.data) {
                  this.TableList = msg.data.data;
                  this.TableList.forEach((e) => {
                    this.myChartX.push(e.datetime);
                    this.myChartY.push(e.value);
                  });
                  this.myChartShow = true;
                } else {
                  this.$message.error("获取数据列表失败");
                }
                this.Tableloading = false;
                break;
              default:
                break;
            }
          }
          break;
        case 1007:
          switch (msg.funCode) {
            case 0:
              if (checkSpecialId(msg)) {
                if (msg.retCode != 0 || !msg.data) {
                  return this.$message.error(msg.retMsg);
                }
                msg.data.map((e) => {
                  return this.GwList.push({
                    name: e.name,
                    id: e.id,
                  });
                });
                break;
              }
          }
          break;
        case 1008:
          if (checkSpecialId(msg)) {
            switch (msg.funCode) {
              case 0:
                if (msg.retCode != 0 || !msg.data) {
                  return this.$message.error(msg.retMsg);
                }
                this.ZdList = [];
                let list = [{ name: "全选", id: "all" }];
                msg.data.forEach((e) => {
                  list.push({
                    name: e.name,
                    id: e.id,
                  });
                });
                this.ZdList = list;
                break;
              default:
                break;
            }
          }
          break;
        case 1009:
          switch (msg.funCode) {
            case 0:
              if (checkSpecialId(msg)) {
                if (msg.retCode != 0 || !msg.data) {
                  return this.$message.error(msg.retMsg);
                }
                let res = msg.data;
                res.map((e) => {
                  return this.yxList.push({
                    name: e.name,
                    id: e.id,
                  });
                });
              }
              break;
            default:
              break;
          }
          break;
        case 1010:
          switch (msg.funCode) {
            case 0:
              if (checkSpecialId(msg)) {
                if (msg.retCode != 0 || !msg.data) {
                  return this.$message.error(msg.retMsg);
                }
                let res = msg.data;
                res.map((e) => {
                  return this.ycList.push({
                    name: e.name,
                    id: e.id,
                  });
                });
              }
              break;
            default:
              break;
          }
          break;
        case 1011:
          switch (msg.funCode) {
            case 0:
              if (checkSpecialId(msg)) {
                if (msg.retCode != 0 || !msg.data) {
                  return this.$message.error(msg.retMsg);
                }
                let res = msg.data;
                res.map((e) => {
                  return this.ymList.push({
                    name: e.name,
                    id: e.id,
                  });
                });
              }
              break;
            default:
              break;
          }
          break;
        case 1015:
          switch (msg.funCode) {
            case 0:
              if (checkSpecialId(msg)) {
                if (msg.retCode != 0 || !msg.data) {
                  return this.$message.error(msg.retMsg);
                }
                let res = msg.data;
                res.map((e) => {
                  return this.taskList.push({
                    name: e.name,
                    id: e.id,
                  });
                });
              }
              break;
            default:
              break;
          }
          break;

        default:
          break;
      }
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.options = this.value;
    setMessageCallback(this.onMessage);
    publishMsg({
      webMsgType: 1007, //发送网关消息
      funCode: 0,
    });
  },
  destroyed() {
    removeMessageCallback(this.onMessage);
    window.removeEventListener("resize", () => {
      this.myChart.resize();
    });
  },
};
</script>
<style lang="scss" scoped>
.dataQuery {
  @import "./css/index.scss";
  ::v-deep .query-tab {
    border: 0;

    .el-tabs__header {
      margin: 0;
      .el-tabs__nav {
        .el-tabs__item {
          background-color: #242f3b;
          border: 0px;
          color: #bfcbd9;
          padding: 0;
        }

        .el-tabs__item.is-active {
          background-color: #31455d;
          color: #409eff;
        }
      }
    }

    .el-tabs__content {
      // background-color: #05224d;
      height: auto !important;
      overflow-x: hidden;
      overflow-y: auto;

      .el-tab-pane {
        color: #bfcbd9;
      }

      &::-webkit-scrollbar {
        width: 5px;
        height: 14px;
      }

      &::-webkit-scrollbar-track,
      &::-webkit-scrollbar-thumb {
        border-radius: 1px;
        border: 0 solid transparent;
      }

      &::-webkit-scrollbar-track-piece {
        /*修改滚动条的背景和圆角*/
        background: #29405c;
        -webkit-border-radius: 7px;
      }

      &::-webkit-scrollbar-track {
        box-shadow: 1px 1px 5px rgba(116, 148, 170, 0.5) inset;
      }

      &::-webkit-scrollbar-thumb {
        min-height: 20px;
        background-clip: content-box;
        box-shadow: 0 0 0 5px rgba(116, 148, 170, 0.5) inset;
      }

      &::-webkit-scrollbar-corner {
        background: transparent;
      }

      /*修改垂直滚动条的样式*/
      &::-webkit-scrollbar-thumb:vertical {
        background-color: #00113a;
        -webkit-border-radius: 7px;
      }

      /*修改水平滚动条的样式*/
      &::-webkit-scrollbar-thumb:horizontal {
        background-color: #00113a;
        -webkit-border-radius: 7px;
      }
    }
  }
  ::v-deep .el-card {
    border: none;
    background-color: #0a74ff96;
  }
  ::v-deep .el-form-item .el-form-item__label {
    color: #fff;
  }
  ::v-deep .el-select .el-input__inner {
    background-color: transparent;
    border: 1px solid #0099ff;
    color: #fff;
  }
  ::v-deep .el-input__inner {
    background-color: transparent;
    border: 1px solid #0099ff;
    color: #fff;
  }
  ::v-deep .el-select .el-input .el-select__caret {
    color: #fff;
  }
  ::v-deep .el-select .el-select-dropdown {
    border: 1px solid red;
    background-color: transparent;
  }
  ::v-deep .el-select .el-select-dropdown__item {
    color: #fff;
  }
  ::v-deep .el-select .el-select-dropdown__item:hover {
    background-color: transparent;
  }
}

::v-deep .el-empty__description p {
  color: #12fffe;
  font-weight: 500;
  font-size: 16px;
}
// ::v-deep .dataQuery .query-tab .el-tabs__content {
//   height: auto !important;
//   // background-color: #242a30;
// }
// ::v-deep .el-tabs--border-card > .el-tabs__content {
//   // padding: 0px;
// }
</style>
